package com.wk.warehouse.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wk.warehouse.dto.AssignRoleDto;
import com.wk.warehouse.dto.AuthUpdateDto;
import com.wk.warehouse.dto.UserDto;
import com.wk.warehouse.entity.*;
import com.wk.warehouse.exception.BusinessException;
import com.wk.warehouse.page.Page;
import com.wk.warehouse.service.*;
import com.wk.warehouse.util.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * 用户管理后台
 */
@RestController
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;
	@Autowired
	private AuthService authService;
	@Autowired
	private RoleService roleService;

	/**
	 * 获取当前登录用户权限列表
	 */
	@GetMapping("/auth-list")
	public Result authList(@RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String clientToken) {
		CurrentUser currentUser = TokenUtils.getCurrentUser(clientToken);
		List<Auth> authList = authService.findFirstAuth(currentUser.getUserId());
		return Result.ok(authList);
	}

	/**
	 * 导出数据
	 */
	@GetMapping("/exportTable")
	public Result exportTable(Page page, User searchUser){
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		page = new Page(999, 1); // 导出模糊查询所有数据
		hashMap.put("page", page);
		hashMap.put("user", searchUser);
		// 要导出的数据
		List<User> userList = userService.selectUserPage(hashMap);
		return Result.ok(userList);
	}

	/**
	 * 添加用户
	 */
	@PostMapping("/addUser")
	public Result addUser(@RequestBody User user, @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String clientToken) {
		// 获取创建人id
		CurrentUser currentUser = TokenUtils.getCurrentUser(clientToken);
		int userId = currentUser.getUserId(); // 创建人
		// 将查到的用户id设置到创建人属性中
		user.setCreateBy(userId);

		// 获取用户名
		String userCode = user.getUserCode();
		// 通过用户名查找用户，判断是否存在
		User tableUser = userService.findUserByCode(userCode);
		if(tableUser!=null){
			return Result.err(Result.CODE_ERR_BUSINESS, "该用户已存在");
		}
		userService.addUser(user);
		return Result.ok("添加用户成功！");
	}

	/**
	 * 删除用户
	 */
	@DeleteMapping("/deleteUser/{userId}")
	public Result deleteById(@PathVariable Integer userId) {
		userService.deleteUser(userId);
		return Result.ok("删除用户成功！");
	}

	/**
	 * 批量删除用户
	 */
	@DeleteMapping("/deleteUserList")
	public Result deleteById(@RequestBody List<Integer> userIds) {
		userService.deleteUserList(userIds);
		return Result.ok("批量删除用户成功！");
	}

	/**
	 * 修改用户信息
	 */
	@PutMapping("/updateUser")
	public Result updateUser(@RequestBody User userUpdate, @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String clientToken) {
		// 当前登录用户
		CurrentUser currentUser = TokenUtils.getCurrentUser(clientToken);
		int updateBy = currentUser.getUserId();

		userUpdate.setUpdateBy(updateBy);
		int updateRows = userService.updateUser(userUpdate);
		if(updateRows>0){
			return Result.ok("修改成功！");
		}else{
			return Result.err(Result.CODE_ERR_SYS, "修改失败！");
		}
	}

	/**
	 * 重置密码
	 */
	@PutMapping("/updatePwd/{userId}")
	public Result updatePwd(@PathVariable Integer userId) {
		int updateRows = userService.updatePwd(userId);
		if(updateRows>0){
			return Result.ok("重置密码成功！初始密码为：123456");
		}else{
			return Result.err(Result.CODE_ERR_SYS, "重置密码失败！");
		}
	}

	/**
	 * 修改用户状态
	 */
	@PutMapping("/updateState")
	public Result updateState(@RequestBody User user) {
		int updateRows = userService.updateState(user);
		if(updateRows>0){
			return Result.ok("修改成功！");
		}else{
			return Result.err(Result.CODE_ERR_SYS, "修改失败！");
		}
	}

	/**
	 * 分页查询用户
	 */
	@GetMapping("/user-list")
	public Result userList(User searchUser, Page page) {
		// 根据前端的查询条件查询结果
		HashMap<String, Object> map = new HashMap<>();
		map.put("user", searchUser);
		// 获取总条数
		int totalNum = userService.selectCount(map);
		page.setTotalNum(totalNum);

		map.put("page", page);
		// 根据条件查询
		List<User> userList = userService.selectUserPage(map);
		page.setResultList(userList);
		return Result.ok(page);
	}

	/**
	 * 分配角色
	 */
	@PutMapping("/assignRole")
	public Result assignRole(@RequestBody AssignRoleDto assignRoleDto) {
		int userId = assignRoleDto.getUserId();
		List<String> roleCheckList = assignRoleDto.getRoleCheckList();
		userService.assignRoles(userId, roleCheckList); // 分配角色
		return Result.ok("分配角色成功！");
	}

	/**
	 * 查询用户已有角色
	 */
	@GetMapping("/user-role-list/{userId}")
	public Result userRoleList(@PathVariable Integer userId) {
		// 通过用户id查询已有角色
		List<Role> userRoleList = roleService.userRoleList(userId);
		return Result.ok(userRoleList);
	}

	/**
	 * 获取指定用户权限id
	 */
	@GetMapping("/user-auth")
	public Result userAuth(Integer userId) {
		List<Integer> authIds = new ArrayList<>();
		List<Auth> authList = authService.findFirstAuth(userId);
		for(Auth firstAuth: authList){
			// 添加一级权限id
			authIds.add(firstAuth.getAuthId());
			List<Auth> secondAuthList = firstAuth.getChildAuth();
			for(Auth secondAuth: secondAuthList){
				// 添加二级权限id
				authIds.add(secondAuth.getAuthId());
				List<Auth> thirdAuthList = secondAuth.getChildAuth();
				for(Auth thirdAuth: thirdAuthList){
					// 添加三级权限id
					authIds.add(thirdAuth.getAuthId());
				}
			}
		}
		return Result.ok(authIds);
	}

	/**
	 * 修改权限
	 */
	@PutMapping("/auth-grant")
	public Result authGrant(@RequestBody AuthUpdateDto authUpdateDto){
		List<Integer> authIds = authUpdateDto.getAuthIds();
		int updateoRows = userService.grantAuth(authUpdateDto.getUserId(), authIds);
		if(updateoRows==authIds.size()){
			return Result.ok("修改权限成功！");
		}
		return Result.err(Result.CODE_ERR_SYS, "系统错误，修改失败！");
	}
}
